#include "Precomp.h"
#include "InputManager.h"
#include <string>
#include <sstream>
//some macro to aids keymapping
#define _widen(c) L##c
#define widen(c) _widen(#c)
#define MAPKEY(key) keydict[sf::Key::##key]=widen(key);keydict2[widen(key)]=sf::Key::##key;

InputManager::InputManager(const sf::Input& input)
:input(input)
{
	#include "keycodes.h"
}

void InputManager::mapInput(const SQChar* input, SquirrelObject& hit, SquirrelObject& release)
{
	std::map<const SQChar*,sf::Key::Code,compare>::iterator i=keydict2.find(input);
	
	if(i!=keydict2.end())//if this is a key input
	{//map to key input
		key_hit[(*i).second]=hit;
		key_release[(*i).second]=release;
	}
	else
	{//map to general input
		inputmap_hit[input]=hit;
		inputmap_release[input]=release;
	}
}

void InputManager::onEvent(sf::Event& ev)
{
	SquirrelObject function;
	static const SQChar* mouse[sf::Mouse::Count]={L"MLeft",L"MRight",L"MMiddle",L"MX1",L"MX2"};
	switch(ev.Type)
	{
	case sf::Event::KeyPressed:
		function=key_hit[ev.Key.Code];
	break;
	case sf::Event::KeyReleased:
		function=key_release[ev.Key.Code];
	break;
	case sf::Event::JoyButtonPressed:
	break;
	case sf::Event::JoyButtonReleased:
	break;
	case sf::Event::MouseButtonPressed:
		function=inputmap_hit[mouse[ev.MouseButton.Button]];
	break;
	case sf::Event::MouseButtonReleased:
		function=inputmap_release[mouse[ev.MouseButton.Button]];
	break;
	}
	if(!function.IsNull())
	{
		SquirrelVM::BeginCall(function);
		SquirrelVM::EndCall();
	}
}

bool InputManager::isMouseDown(int button) const
{
	return input.IsMouseButtonDown((sf::Mouse::Button)button);
}

bool InputManager::isKeyDown(const SQChar* key) const
{
	
	return input.IsKeyDown(keydict2[key]);
}

bool InputManager::isJoyDown(unsigned int JoyId, unsigned int Button) const
{
	return input.IsJoystickButtonDown(JoyId, Button);
}

unsigned int InputManager::mouseX() const
{
	return input.GetMouseX();
}

unsigned int InputManager::mouseY() const
{
	return input.GetMouseY();
}
